package gui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedList;

import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.SwingWorker;

import tools.OptionReader;
import contacts.CheckboxBook;

/**
 * Fenster zum Konatkt erstellen
 * 
 * @author Michi
 * 
 */
public class NewContactWindow extends JFrame {

	/**
     * 
     */
	private static final long serialVersionUID = -4833271962040022630L;
	private Connection connection = null;
	private Statement stat;
	private JTextField textField;
	private JTextField textField_1;
	private JTextField textField_2;
	private JTextField textField_3;
	private JTextField textField_4;

	private JTextField textField_6;
	private JTextField textField_7;
	private JTextField textField_8;
	private JTextField textField_9;
	private JTextField textField_10;
	private CheckBoxList books;
	private DefaultListModel dlm;
	private LinkedList<CheckboxBook> llbooks = new LinkedList<CheckboxBook>();
	private OptionReader or;
	private String[] windowColorsSeperated;
	private int r;
	private int g;
	private int b;

	// Sprachen (0 = deutsch; 1 = englisch; 2 = latein)
	int speak = 0;
	String[] titel = { "Kontakt Hinzufuegen", "Add Contact", "amicus adicere" };
	String[] name = { "Name", "name", "nomen" };
	String[] vorname = { "Vorname", "first name", "praenomen" };
	String[] strasse = { "Strasse", "street", "via" };
	String[] plz = { "PLZ", "postcode", "territorium" };
	String[] stadt = { "Stadt", "street", "oppidum" };
	String[] email = { "E-Mail", "mail", "technicus nuntius" };
	String[] geburtstag = { "Geburtstag", "birthday", "diei natalis" };
	String[] telefonHeim = { "Telefon (Heim)", "phone (home)",
			"telephonum (patria)" };
	String[] telefonArbeit = { "Telefon (Arbeit)", "phone (work)",
			"telephonum (opus)" };
	String[] telefonMobil = { "Telefon (Mobil)", "mobile", "telephonum manuale" };
	String[] fax = { "FAX", "fax", "mutoniatus" };
	String[] addButton = { "Hinzufuegen", "Add", "Adicere" };

	//

	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					NewContactWindow frame = new NewContactWindow();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Konstruktor
	 * 
	 * @param acp
	 *            Instanz der AddContactPane
	 */
	@SuppressWarnings({ "deprecation", "unused" })
	public NewContactWindow(final AddContactPane acp) {

		or = new OptionReader();
		try {
			or.getOpionsFromFile();
		} catch (IOException e2) {

			e2.printStackTrace();
		}

		String windowColors = or.getColorSetting();
		windowColorsSeperated = windowColors.split(",");
		r = Integer.parseInt(windowColorsSeperated[0]);
		g = Integer.parseInt(windowColorsSeperated[1]);
		b = Integer.parseInt(windowColorsSeperated[2]);

		speak = Integer.parseInt(or.getLanguage());

		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		Dimension size = new Dimension(600, 500);
		setSize(size);
		setPreferredSize(size);
		setMinimumSize(size);
		setMaximumSize(size);

		setTitle(titel[speak]);
		getContentPane().setBackground(Color.LIGHT_GRAY);
		getContentPane().setLayout(new BorderLayout(0, 0));

		JPanel centerpanel = new JPanel();
		centerpanel.setBackground(new Color(r, g, b));
		getContentPane().add(centerpanel, BorderLayout.CENTER);
		centerpanel.setLayout(null);

		JLabel lblName = new JLabel(name[speak]);
		lblName.setHorizontalAlignment(SwingConstants.RIGHT);
		lblName.setBounds(20, 30, 120, 16);
		centerpanel.add(lblName);

		JLabel lblStrae = new JLabel(strasse[speak]);
		lblStrae.setHorizontalAlignment(SwingConstants.RIGHT);
		lblStrae.setBounds(20, 60, 120, 16);
		centerpanel.add(lblStrae);

		JLabel lblPlz = new JLabel(plz[speak]);
		lblPlz.setHorizontalAlignment(SwingConstants.RIGHT);
		lblPlz.setBounds(20, 90, 120, 16);
		centerpanel.add(lblPlz);

		JLabel lblStadt = new JLabel(stadt[speak]);
		lblStadt.setHorizontalAlignment(SwingConstants.RIGHT);
		lblStadt.setBounds(20, 120, 120, 16);
		centerpanel.add(lblStadt);

		JLabel lblEmail = new JLabel(email[speak]);
		lblEmail.setHorizontalAlignment(SwingConstants.RIGHT);
		lblEmail.setBounds(20, 150, 120, 16);
		centerpanel.add(lblEmail);

		JLabel lblGeburtstag = new JLabel(geburtstag[speak]);
		lblGeburtstag.setHorizontalAlignment(SwingConstants.RIGHT);
		lblGeburtstag.setBounds(20, 180, 120, 16);
		centerpanel.add(lblGeburtstag);

		JLabel lblTelefonheim = new JLabel(telefonHeim[speak]);
		lblTelefonheim.setHorizontalAlignment(SwingConstants.RIGHT);
		lblTelefonheim.setBounds(20, 210, 120, 16);
		centerpanel.add(lblTelefonheim);

		JLabel lblTelefonarbeit = new JLabel(telefonArbeit[speak]);
		lblTelefonarbeit.setHorizontalAlignment(SwingConstants.RIGHT);
		lblTelefonarbeit.setBounds(20, 240, 120, 16);
		centerpanel.add(lblTelefonarbeit);

		JLabel lblFax = new JLabel(fax[speak]);
		lblFax.setHorizontalAlignment(SwingConstants.RIGHT);
		lblFax.setBounds(20, 270, 120, 16);
		centerpanel.add(lblFax);

		JLabel lblTelefonmobil = new JLabel(telefonMobil[speak]);
		lblTelefonmobil.setHorizontalAlignment(SwingConstants.RIGHT);
		lblTelefonmobil.setBounds(20, 300, 120, 16);
		centerpanel.add(lblTelefonmobil);

		textField = new JTextField();
		textField.setBounds(180, 24, 117, 28);
		centerpanel.add(textField);
		textField.setColumns(10);

		textField_1 = new JTextField();
		textField_1.setBounds(180, 54, 344, 28);
		centerpanel.add(textField_1);
		textField_1.setColumns(10);

		textField_2 = new JTextField();
		textField_2.setColumns(10);
		textField_2.setBounds(180, 84, 344, 28);
		centerpanel.add(textField_2);

		textField_3 = new JTextField();
		textField_3.setColumns(10);
		textField_3.setBounds(180, 114, 344, 28);
		centerpanel.add(textField_3);

		textField_4 = new JTextField();
		textField_4.setColumns(10);
		textField_4.setBounds(180, 144, 344, 28);
		centerpanel.add(textField_4);
		//
		// textField_5 = new JTextField();
		// textField_5.setColumns(10);
		// textField_5.setBounds(180, 174, 344, 28);
		// centerpanel.add(textField_5);

		// Datum

		// Jahr //

		Date d = new Date();
		int y = d.getYear();
		int m = d.getMonth() + 1;
		int t = d.getDate();

		String[] jahreArray = new String[y + 2];
		jahreArray[0] = "";
		for (int i = 1; i <= y + 1; i++) {
			jahreArray[i] = Integer.toString(i + 1899);

		}

		final JComboBox jahr = new JComboBox(jahreArray);
		jahr.setSelectedIndex(0);
		// !
		jahr.setBounds(330, 176, 85, 20);
		centerpanel.add(jahr);

		// Monat //

		String[] monatsArray = new String[13];
		monatsArray[0] = "";
		for (int i = 1; i < 13; i++) {
			String s = "";
			if (i < 10) {
				s = "0";
			}
			s += Integer.toString(i);
			monatsArray[i] = s;
		}

		final JComboBox monat = new JComboBox(monatsArray);
		monat.setSelectedIndex(0);

		monat.setBounds(255, 176, 70, 20);
		centerpanel.add(monat);

		// Tag //

		String[] tagesArray = new String[32];
		tagesArray[0] = "";

		for (int i = 1; i < 32; i++) {
			String s = "";
			if (i < 10) {
				s = "0";
			}
			s += Integer.toString(i);
			tagesArray[i] = s;
		}

		final JComboBox tag = new JComboBox(tagesArray);
		tag.setSelectedIndex(0);

		tag.setBounds(180, 176, 70, 20);
		centerpanel.add(tag);

		textField_6 = new JTextField();
		textField_6.setColumns(10);
		textField_6.setBounds(180, 204, 344, 28);
		centerpanel.add(textField_6);

		textField_7 = new JTextField();
		textField_7.setColumns(10);
		textField_7.setBounds(180, 234, 344, 28);
		centerpanel.add(textField_7);

		textField_8 = new JTextField();
		textField_8.setColumns(10);
		textField_8.setBounds(180, 264, 344, 28);
		centerpanel.add(textField_8);

		textField_9 = new JTextField();
		textField_9.setColumns(10);
		textField_9.setBounds(180, 294, 344, 28);
		centerpanel.add(textField_9);

		// 309, 30, 61, 16
		JLabel lblVorname = new JLabel(vorname[speak]);
		lblVorname.setBounds(304, 30, 71, 16);
		centerpanel.add(lblVorname);

		// 382, 24, 142, 28
		textField_10 = new JTextField();
		textField_10.setBounds(382, 24, 142, 28);
		centerpanel.add(textField_10);
		textField_10.setColumns(10);

		dlm = new DefaultListModel();
		books = new CheckBoxList();
		books.setModel(dlm);
		// ////////////////////////////////////////////////////////////////////////
		// /////////////////////////////////////////////////////////////////////////////
		// /////////////////////////////////////////////////////////////////////////////

		try {
			Class.forName("com.mysql.jdbc.Driver");
			connection = DriverManager
					.getConnection("jdbc:mysql://win9142.informatik.uni-wuerzburg.de:3306?user=awesomefireballs&password=jesus");
		} catch (ClassNotFoundException e) {

			e.printStackTrace();
		} catch (SQLException e) {

			e.printStackTrace();

		}
		try {
			stat = connection.createStatement();
			stat.executeQuery("use `sopra-ws12-awesome_fireballs`;");

			ResultSet idsBooks = stat
					.executeQuery("SELECT idBooks, name, idCreator FROM Books WHERE idUser = "
							+ Test.iduser + ";");
			boolean atleastone = false;
			while (idsBooks.next()) {

				CheckboxBook temp = new CheckboxBook(
						idsBooks.getInt("idBooks"), idsBooks.getString("name"),
						idsBooks.getInt("idCreator"));

				// Fuegt alle Personen interner Liste zu um spaeter wieder auf
				// id
				// zurueckgreifen zu koennen.
				llbooks.add(temp);

				JCheckBoxWithObject check = new JCheckBoxWithObject(temp);
				if(atleastone == false){
					check.setSelected(true);
					atleastone = true;
				}

				dlm.addElement(check);

			}

		} catch (SQLException e1) {
			e1.printStackTrace();
		}

		JScrollPane bookscroller = new JScrollPane(books);
		bookscroller.setBounds(180, 324, 344, 28 * 3);
		// bookscroller.setPreferredSize(new Dimension(280, 570));
		centerpanel.add(bookscroller);

		JButton btnKontaktHinzufgen = new JButton(addButton[speak]);
		btnKontaktHinzufgen.setBounds(347, 415, 177, 29);
		centerpanel.add(btnKontaktHinzufgen);

		// ActionListener f�r Kontakt hinzuf�gen

		ActionListener bu = new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				if (textField.getText().equals("") == true) {
					JOptionPane
							.showMessageDialog(
									null,
									"Es muss ein Nachname gesetzt werden! (falls sie nur einen Namen setzten wollen, dann verwenden sie bitte das Feld Nachname)",
									"Haaalt! Stop!", JOptionPane.ERROR_MESSAGE);
				} else {
					@SuppressWarnings("rawtypes")
					SwingWorker worker = new SwingWorker() {
						@SuppressWarnings("unchecked")
						@Override
						public Object doInBackground() {
							try {
								Class.forName("com.mysql.jdbc.Driver");
								connection = DriverManager
										.getConnection("jdbc:mysql://win9142.informatik.uni-wuerzburg.de:3306?user=awesomefireballs&password=jesus");

							} catch (ClassNotFoundException e) {
								e.printStackTrace();
							} catch (SQLException e) {
								e.printStackTrace();
								return false;
							}

							Statement stat = null;

							// //////// Date auslesen //////////

							int aY = 0;
							int aM = 0;
							int aD = 0;

							if (jahr.getSelectedIndex() != 0
									&& monat.getSelectedIndex() != 0
									&& tag.getSelectedIndex() != 0) {

								aY = Integer.parseInt((String) jahr
										.getSelectedItem());

								aM = monat.getSelectedIndex();
								aD = tag.getSelectedIndex();

							}

							// Prüft ob der Monat so viele Tage hat.

							if (aD > monthLength(new Date(aY - 1900, aM - 1, 1))) {

								new NotifyFrame(
										"Dieser Monat besitzt diesen Tag nicht.")
										.setVisible(true);
							}

							else {

								Date setDate = null;
								if (aY != 0 && aM != 0 && aD != 0) {
									setDate = makeDate(aY, aM, aD);
								}

								try {
									stat = connection.createStatement();

									String lname = textField.getText();
									String fname = textField_10.getText();
									String street = textField_1.getText();
									String zip = textField_2.getText();
									String town = textField_3.getText();
									String email = textField_4.getText();
									// String bday = textField_5.getText();
									String telehome = textField_6.getText();
									String telework = textField_7.getText();
									String fax = textField_8.getText();
									String cell = textField_9.getText();

									// Formt das Date in einen korrekten String.
									SimpleDateFormat sdf = new SimpleDateFormat(
											"yyyy-MM-dd");

									String bday = "";

									if (setDate != null) {
										StringBuilder sB = new StringBuilder(
												sdf.format(setDate));
										bday = sB.toString();
									}

									System.out.println(bday);

									stat.executeQuery("use `sopra-ws12-awesome_fireballs`;");
									int idAdress = 0;
									ResultSet rs = stat
											.executeQuery("SELECT idAdress FROM `sopra-ws12-awesome_fireballs`.`Adress`ORDER BY idAdress DESC LIMIT 1;");
									while (rs.next()) {
										idAdress = rs.getInt(1) + 1;
									}

									// ResultSet party = stat
									// .executeQuery("SELECT COUNT(idAdress) FROM `sopra-ws12-awesome_fireballs`.Adress;");
									//
									// while (party.next()) {
									// idAdress = party.getInt(1) + 1;
									// }
									connection.setAutoCommit(false);
									PreparedStatement pstmt = connection
											.prepareStatement("INSERT INTO Adress VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
									pstmt.setInt(1, idAdress);
									pstmt.setString(2, fname);
									pstmt.setString(3, lname);
									pstmt.setString(4, street);
									pstmt.setString(5, zip);
									pstmt.setString(6, town);
									pstmt.setString(7, email);
									pstmt.setString(8, bday);
									pstmt.setString(9, telehome);
									pstmt.setString(10, telework);
									pstmt.setString(11, fax);
									pstmt.setString(12, cell);
									pstmt.addBatch();

									PreparedStatement psentrys = connection
											.prepareStatement("INSERT INTO Entrys VALUES( ?, ?, ?)");

									int idEntrys = 0;
									ResultSet entrys = stat
											.executeQuery("SELECT idEntrys FROM `sopra-ws12-awesome_fireballs`.`Entrys`ORDER BY idEntrys DESC LIMIT 1;");
									while (entrys.next()) {
										idEntrys = entrys.getInt(1) + 1;
									}

									// ////neuer Teil für Adressbücher//////
									LinkedList idadd = new LinkedList<Integer>();

									for (int i = 0; i < dlm.size(); i++) {
										JCheckBoxWithObject temp = (JCheckBoxWithObject) dlm
												.get(i);
										if (temp.isSelected() == true) {
											CheckboxBook temp2 = (CheckboxBook) temp
													.getObject();
											idadd.add(temp2.getIdBooks());
										}

									}

									pstmt.executeBatch();

									for (int i = 0; i < idadd.size(); i++) {
										psentrys.setInt(1, idEntrys + i);
										psentrys.setInt(2, idAdress);
										psentrys.setInt(3,
												(Integer) idadd.get(i));
										psentrys.addBatch();
										System.out.println(psentrys.toString());
									}

									psentrys.executeBatch();

									connection.commit();
									connection.setAutoCommit(true);
								} catch (SQLException e) {
									e.printStackTrace();
								}
								return stat;

							}
							return null;
						}

						@Override
						public void done() {

							acp.update();
							acp.setListselectionactivated(true);

							dispose();
						}
					};
					worker.execute();
				}
			}

		};

		btnKontaktHinzufgen.addActionListener(bu);

	}

	@SuppressWarnings({ "deprecation", "unused" })
	public NewContactWindow() {

		or = new OptionReader();
		try {
			or.getOpionsFromFile();
		} catch (IOException e2) {

			e2.printStackTrace();
		}

		String windowColors = or.getColorSetting();
		windowColorsSeperated = windowColors.split(",");
		r = Integer.parseInt(windowColorsSeperated[0]);
		g = Integer.parseInt(windowColorsSeperated[1]);
		b = Integer.parseInt(windowColorsSeperated[2]);

		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		Dimension size = new Dimension(600, 450);
		setSize(size);
		setPreferredSize(size);
		setMinimumSize(size);
		setMaximumSize(size);

		setTitle("Kontakt Hinzufuegen");
		getContentPane().setBackground(new Color(r, g, b));
		getContentPane().setLayout(new BorderLayout(0, 0));

		JPanel centerpanel = new JPanel();
		centerpanel.setBackground(new Color(r, g, b));
		getContentPane().add(centerpanel, BorderLayout.CENTER);
		centerpanel.setLayout(null);

		JLabel lblName = new JLabel("Name");
		lblName.setHorizontalAlignment(SwingConstants.RIGHT);
		lblName.setBounds(50, 30, 97, 16);
		centerpanel.add(lblName);

		JLabel lblStrae = new JLabel("Strasse");
		lblStrae.setHorizontalAlignment(SwingConstants.RIGHT);
		lblStrae.setBounds(50, 60, 97, 16);
		centerpanel.add(lblStrae);

		JLabel lblPlz = new JLabel("PLZ");
		lblPlz.setHorizontalAlignment(SwingConstants.RIGHT);
		lblPlz.setBounds(50, 90, 97, 16);
		centerpanel.add(lblPlz);

		JLabel lblStadt = new JLabel("Stadt");
		lblStadt.setHorizontalAlignment(SwingConstants.RIGHT);
		lblStadt.setBounds(50, 120, 97, 16);
		centerpanel.add(lblStadt);

		JLabel lblEmail = new JLabel("Email");
		lblEmail.setHorizontalAlignment(SwingConstants.RIGHT);
		lblEmail.setBounds(50, 150, 97, 16);
		centerpanel.add(lblEmail);

		JLabel lblGeburtstag = new JLabel("Geburtstag");
		lblGeburtstag.setHorizontalAlignment(SwingConstants.RIGHT);
		lblGeburtstag.setBounds(50, 180, 97, 16);
		centerpanel.add(lblGeburtstag);

		JLabel lblTelefonheim = new JLabel("Telefon (Heim)");
		lblTelefonheim.setHorizontalAlignment(SwingConstants.RIGHT);
		lblTelefonheim.setBounds(50, 210, 97, 16);
		centerpanel.add(lblTelefonheim);

		JLabel lblTelefonarbeit = new JLabel("Telefon (Arbeit)");
		lblTelefonarbeit.setHorizontalAlignment(SwingConstants.RIGHT);
		lblTelefonarbeit.setBounds(50, 240, 97, 16);
		centerpanel.add(lblTelefonarbeit);

		JLabel lblFax = new JLabel("Fax");
		lblFax.setHorizontalAlignment(SwingConstants.RIGHT);
		lblFax.setBounds(50, 270, 97, 16);
		centerpanel.add(lblFax);

		JLabel lblTelefonmobil = new JLabel("Telefon (Mobil)");
		lblTelefonmobil.setHorizontalAlignment(SwingConstants.RIGHT);
		lblTelefonmobil.setBounds(50, 300, 97, 16);
		centerpanel.add(lblTelefonmobil);

		textField = new JTextField();
		textField.setBounds(180, 24, 117, 28);
		centerpanel.add(textField);
		textField.setColumns(10);

		JLabel lblAdressbuch = new JLabel("Adressbuch");
		lblAdressbuch.setHorizontalAlignment(SwingConstants.RIGHT);
		lblAdressbuch.setBounds(50, 329, 97, 16);
		centerpanel.add(lblAdressbuch);

		textField_1 = new JTextField();
		textField_1.setBounds(180, 54, 344, 28);
		centerpanel.add(textField_1);
		textField_1.setColumns(10);

		textField_2 = new JTextField();
		textField_2.setColumns(10);
		textField_2.setBounds(180, 84, 344, 28);
		centerpanel.add(textField_2);

		textField_3 = new JTextField();
		textField_3.setColumns(10);
		textField_3.setBounds(180, 114, 344, 28);
		centerpanel.add(textField_3);

		textField_4 = new JTextField();
		textField_4.setColumns(10);
		textField_4.setBounds(180, 144, 344, 28);
		centerpanel.add(textField_4);
		//
		// textField_5 = new JTextField();
		// textField_5.setColumns(10);
		// textField_5.setBounds(180, 174, 344, 28);
		// centerpanel.add(textField_5);

		// Datum

		// Jahr //

		Date d = new Date();
		int y = d.getYear();
		int m = d.getMonth() + 1;
		int t = d.getDate();

		String[] jahreArray = new String[y + 2];
		jahreArray[0] = "";
		for (int i = 1; i <= y + 1; i++) {
			jahreArray[i] = Integer.toString(i + 1899);

		}

		final JComboBox jahr = new JComboBox(jahreArray);
		jahr.setSelectedIndex(0);
		// !
		jahr.setBounds(330, 176, 85, 20);
		centerpanel.add(jahr);

		// Monat //

		String[] monatsArray = new String[13];
		monatsArray[0] = "";
		for (int i = 1; i < 13; i++) {
			String s = "";
			if (i < 10) {
				s = "0";
			}
			s += Integer.toString(i);
			monatsArray[i] = s;
		}

		final JComboBox monat = new JComboBox(monatsArray);
		monat.setSelectedIndex(0);

		monat.setBounds(255, 176, 70, 20);
		centerpanel.add(monat);

		// Tag //

		String[] tagesArray = new String[32];
		tagesArray[0] = "";

		for (int i = 1; i < 32; i++) {
			String s = "";
			if (i < 10) {
				s = "0";
			}
			s += Integer.toString(i);
			tagesArray[i] = s;
		}

		final JComboBox tag = new JComboBox(tagesArray);
		tag.setSelectedIndex(0);

		tag.setBounds(180, 176, 70, 20);
		centerpanel.add(tag);

		textField_6 = new JTextField();
		textField_6.setColumns(10);
		textField_6.setBounds(180, 204, 344, 28);
		centerpanel.add(textField_6);

		textField_7 = new JTextField();
		textField_7.setColumns(10);
		textField_7.setBounds(180, 234, 344, 28);
		centerpanel.add(textField_7);

		textField_8 = new JTextField();
		textField_8.setColumns(10);
		textField_8.setBounds(180, 264, 344, 28);
		centerpanel.add(textField_8);

		textField_9 = new JTextField();
		textField_9.setColumns(10);
		textField_9.setBounds(180, 294, 344, 28);
		centerpanel.add(textField_9);

		JLabel lblVorname = new JLabel("Vorname");
		lblVorname.setBounds(309, 30, 80, 16);
		centerpanel.add(lblVorname);

		textField_10 = new JTextField();
		textField_10.setBounds(382, 24, 142, 28);
		centerpanel.add(textField_10);
		textField_10.setColumns(10);

		JButton btnKontaktHinzufgen = new JButton("Kontakt Hinzufügen");
		btnKontaktHinzufgen.setBounds(347, 380, 177, 28);
		centerpanel.add(btnKontaktHinzufgen);

		dlm = new DefaultListModel();
		books = new CheckBoxList();
		books.setModel(dlm);
		// ////////////////////////////////////////////////////////////////////////
		// /////////////////////////////////////////////////////////////////////////////
		// /////////////////////////////////////////////////////////////////////////////

		try {
			Class.forName("com.mysql.jdbc.Driver");
			connection = DriverManager
					.getConnection("jdbc:mysql://win9142.informatik.uni-wuerzburg.de:3306?user=awesomefireballs&password=jesus");
		} catch (ClassNotFoundException e) {

			e.printStackTrace();
		} catch (SQLException e) {

			e.printStackTrace();

		}
		try {
			stat = connection.createStatement();
			stat.executeQuery("use `sopra-ws12-awesome_fireballs`;");

			ResultSet idsBooks = stat
					.executeQuery("SELECT idBooks, name, idCreator FROM Books WHERE idUser = "
							+ Test.iduser + ";");

			while (idsBooks.next()) {

				CheckboxBook temp = new CheckboxBook(
						idsBooks.getInt("idBooks"), idsBooks.getString("name"),
						idsBooks.getInt("idCreator"));

				// Fuegt alle Personen interner Liste zu um spaeter wieder auf
				// id
				// zurueckgreifen zu koennen.
				llbooks.add(temp);

				JCheckBoxWithObject check = new JCheckBoxWithObject(temp);

				dlm.addElement(check);

			}

		} catch (SQLException e1) {
			e1.printStackTrace();
		}

		JScrollPane bookscroller = new JScrollPane(books);
		bookscroller.setBounds(180, 324, 344, 28 * 3);
		// bookscroller.setPreferredSize(new Dimension(280, 570));
		centerpanel.add(bookscroller);

		// ActionListener f�r Kontakt hinzuf�gen

		ActionListener bu = new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {

				@SuppressWarnings("rawtypes")
				SwingWorker worker = new SwingWorker() {
					@SuppressWarnings("unchecked")
					@Override
					public Object doInBackground() {
						try {
							Class.forName("com.mysql.jdbc.Driver");
							connection = DriverManager
									.getConnection("jdbc:mysql://win9142.informatik.uni-wuerzburg.de:3306?user=awesomefireballs&password=jesus");

						} catch (ClassNotFoundException e) {
							e.printStackTrace();
						} catch (SQLException e) {
							e.printStackTrace();
							return false;
						}

						Statement stat = null;

						// //////// Date auslesen //////////

						int aY = 0;
						int aM = 0;
						int aD = 0;

						if (jahr.getSelectedIndex() != 0
								&& monat.getSelectedIndex() != 0
								&& tag.getSelectedIndex() != 0) {

							aY = Integer.parseInt((String) jahr
									.getSelectedItem());

							aM = monat.getSelectedIndex();
							aD = tag.getSelectedIndex();

						}

						// Prüft ob der Monat so viele Tage hat.

						if (aD > monthLength(new Date(aY - 1900, aM - 1, 1))) {

							new NotifyFrame(
									"Dieser Monat besitzt diesen Tag nicht.")
									.setVisible(true);
						}

						else {

							Date setDate = null;
							if (aY != 0 && aM != 0 && aD != 0) {
								setDate = makeDate(aY, aM, aD);
							}

							try {
								stat = connection.createStatement();

								String fname = textField.getText();
								String lname = textField_10.getText();
								String street = textField_1.getText();
								String zip = textField_2.getText();
								String town = textField_3.getText();
								String email = textField_4.getText();
								// String bday = textField_5.getText();
								String telehome = textField_6.getText();
								String telework = textField_7.getText();
								String fax = textField_8.getText();
								String cell = textField_9.getText();

								// Formt das Date in einen korrekten String.
								SimpleDateFormat sdf = new SimpleDateFormat(
										"yyyy-MM-dd");

								String bday = "";

								if (setDate != null) {
									StringBuilder sB = new StringBuilder(
											sdf.format(setDate));
									bday = sB.toString();
								}

								System.out.println(bday);

								stat.executeQuery("use `sopra-ws12-awesome_fireballs`;");
								int idAdress = 0;
								ResultSet rs = stat
										.executeQuery("SELECT idAdress FROM `sopra-ws12-awesome_fireballs`.`Adress`ORDER BY idAdress DESC LIMIT 1;");
								while (rs.next()) {
									idAdress = rs.getInt(1) + 1;
								}

								// ResultSet party = stat
								// .executeQuery("SELECT COUNT(idAdress) FROM `sopra-ws12-awesome_fireballs`.Adress;");
								//
								// while (party.next()) {
								// idAdress = party.getInt(1) + 1;
								// }
								connection.setAutoCommit(false);
								PreparedStatement pstmt = connection
										.prepareStatement("INSERT INTO Adress VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
								pstmt.setInt(1, idAdress);
								pstmt.setString(2, fname);
								pstmt.setString(3, lname);
								pstmt.setString(4, street);
								pstmt.setString(5, zip);
								pstmt.setString(6, town);
								pstmt.setString(7, email);
								pstmt.setString(8, bday);
								pstmt.setString(9, telehome);
								pstmt.setString(10, telework);
								pstmt.setString(11, fax);
								pstmt.setString(12, cell);
								pstmt.addBatch();

								PreparedStatement psentrys = connection
										.prepareStatement("INSERT INTO Entrys VALUES( ?, ?, ?)");

								int idEntrys = 0;
								ResultSet entrys = stat
										.executeQuery("SELECT idEntrys FROM `sopra-ws12-awesome_fireballs`.`Entrys`ORDER BY idEntrys DESC LIMIT 1;");
								while (entrys.next()) {
									idEntrys = entrys.getInt(1) + 1;
								}
								// ///neuer Teil für Adressbücher//////
								LinkedList idadd = new LinkedList<Integer>();

								for (int i = 0; i < dlm.size(); i++) {
									JCheckBoxWithObject temp = (JCheckBoxWithObject) dlm
											.get(i);
									if (temp.isSelected() == true) {
										CheckboxBook temp2 = (CheckboxBook) temp
												.getObject();
										idadd.add(temp2.getIdBooks());
									}

								}

								pstmt.executeBatch();

								for (int i = 0; i < idadd.size(); i++) {
									psentrys.setInt(1, idEntrys + i);
									psentrys.setInt(2, idAdress);
									psentrys.setInt(3, (Integer) idadd.get(i));
									psentrys.addBatch();
									System.out.println(psentrys.toString());
								}

								psentrys.executeBatch();
								connection.commit();
								connection.setAutoCommit(true);
							} catch (SQLException e) {
								e.printStackTrace();
							}
							return stat;

						}
						return null;
					}

					@Override
					public void done() {

						dispose();

					}
				};
				worker.execute();

			}

		};

		btnKontaktHinzufgen.addActionListener(bu);

	}

	@SuppressWarnings({ "deprecation", "unused" })
	public NewContactWindow(String email) {

		or = new OptionReader();
		try {
			or.getOpionsFromFile();
		} catch (IOException e2) {

			e2.printStackTrace();
		}

		String windowColors = or.getColorSetting();
		windowColorsSeperated = windowColors.split(",");
		r = Integer.parseInt(windowColorsSeperated[0]);
		g = Integer.parseInt(windowColorsSeperated[1]);
		b = Integer.parseInt(windowColorsSeperated[2]);

		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		Dimension size = new Dimension(600, 500);
		setSize(size);
		setPreferredSize(size);
		setMinimumSize(size);
		setMaximumSize(size);

		setTitle("Kontakt Hinzufuegen");
		getContentPane().setBackground(new Color(r, g, b));
		getContentPane().setLayout(new BorderLayout(0, 0));

		JPanel centerpanel = new JPanel();
		centerpanel.setBackground(new Color(r, g, b));
		getContentPane().add(centerpanel, BorderLayout.CENTER);
		centerpanel.setLayout(null);

		JLabel lblName = new JLabel("Name");
		lblName.setHorizontalAlignment(SwingConstants.RIGHT);
		lblName.setBounds(50, 30, 97, 16);
		centerpanel.add(lblName);

		JLabel lblStrae = new JLabel("Strasse");
		lblStrae.setHorizontalAlignment(SwingConstants.RIGHT);
		lblStrae.setBounds(50, 58, 97, 16);
		centerpanel.add(lblStrae);

		JLabel lblPlz = new JLabel("PLZ");
		lblPlz.setHorizontalAlignment(SwingConstants.RIGHT);
		lblPlz.setBounds(50, 86, 97, 16);
		centerpanel.add(lblPlz);

		JLabel lblStadt = new JLabel("Stadt");
		lblStadt.setHorizontalAlignment(SwingConstants.RIGHT);
		lblStadt.setBounds(50, 114, 97, 16);
		centerpanel.add(lblStadt);

		JLabel lblEmail = new JLabel("Email");
		lblEmail.setHorizontalAlignment(SwingConstants.RIGHT);
		lblEmail.setBounds(50, 142, 97, 16);
		centerpanel.add(lblEmail);

		JLabel lblGeburtstag = new JLabel("Geburtstag");
		lblGeburtstag.setHorizontalAlignment(SwingConstants.RIGHT);
		lblGeburtstag.setBounds(50, 170, 97, 16);
		centerpanel.add(lblGeburtstag);

		JLabel lblTelefonheim = new JLabel("Telefon (Heim)");
		lblTelefonheim.setHorizontalAlignment(SwingConstants.RIGHT);
		lblTelefonheim.setBounds(50, 198, 97, 16);
		centerpanel.add(lblTelefonheim);

		JLabel lblTelefonarbeit = new JLabel("Telefon (Arbeit)");
		lblTelefonarbeit.setHorizontalAlignment(SwingConstants.RIGHT);
		lblTelefonarbeit.setBounds(50, 226, 97, 16);
		centerpanel.add(lblTelefonarbeit);

		JLabel lblFax = new JLabel("Fax");
		lblFax.setHorizontalAlignment(SwingConstants.RIGHT);
		lblFax.setBounds(50, 282, 97, 16);
		centerpanel.add(lblFax);

		JLabel lblTelefonmobil = new JLabel("Telefon (Mobil)");
		lblTelefonmobil.setHorizontalAlignment(SwingConstants.RIGHT);
		lblTelefonmobil.setBounds(50, 254, 97, 16);
		centerpanel.add(lblTelefonmobil);

		textField = new JTextField();
		textField.setBounds(180, 24, 117, 28);
		centerpanel.add(textField);
		textField.setColumns(10);

		textField_1 = new JTextField();
		textField_1.setBounds(180, 52, 344, 28);
		centerpanel.add(textField_1);
		textField_1.setColumns(10);

		textField_2 = new JTextField();
		textField_2.setColumns(10);
		textField_2.setBounds(180, 80, 344, 28);
		centerpanel.add(textField_2);

		textField_3 = new JTextField();
		textField_3.setColumns(10);
		textField_3.setBounds(180, 108, 344, 28);
		centerpanel.add(textField_3);

		textField_4 = new JTextField();
		textField_4.setText(email);
		textField_4.setColumns(10);
		textField_4.setBounds(180, 136, 344, 28);
		centerpanel.add(textField_4);

		// textField_5 = new JTextField();
		// textField_5.setColumns(10);
		// textField_5.setBounds(180, 164, 344, 28);
		// centerpanel.add(textField_5);

		// Datum

		// Jahr //

		Date d = new Date();
		int y = d.getYear();
		int m = d.getMonth() + 1;
		int t = d.getDate();

		String[] jahreArray = new String[y + 2];
		jahreArray[0] = "";
		for (int i = 1; i <= y + 1; i++) {
			jahreArray[i] = Integer.toString(i + 1899);

		}

		final JComboBox jahr = new JComboBox(jahreArray);
		jahr.setSelectedIndex(0);
		// !
		jahr.setBounds(330, 176, 85, 20);
		centerpanel.add(jahr);

		// Monat //

		String[] monatsArray = new String[13];
		monatsArray[0] = "";
		for (int i = 1; i < 13; i++) {
			String s = "";
			if (i < 10) {
				s = "0";
			}
			s += Integer.toString(i);
			monatsArray[i] = s;
		}

		final JComboBox monat = new JComboBox(monatsArray);
		monat.setSelectedIndex(0);

		monat.setBounds(255, 176, 70, 20);
		centerpanel.add(monat);

		// Tag //

		String[] tagesArray = new String[32];
		tagesArray[0] = "";

		for (int i = 1; i < 32; i++) {
			String s = "";
			if (i < 10) {
				s = "0";
			}
			s += Integer.toString(i);
			tagesArray[i] = s;
		}

		final JComboBox tag = new JComboBox(tagesArray);
		tag.setSelectedIndex(0);

		tag.setBounds(180, 176, 70, 20);
		centerpanel.add(tag);

		textField_6 = new JTextField();
		textField_6.setColumns(10);
		textField_6.setBounds(180, 204, 344, 28);
		centerpanel.add(textField_6);

		textField_7 = new JTextField();
		textField_7.setColumns(10);
		textField_7.setBounds(180, 234, 344, 28);
		centerpanel.add(textField_7);

		textField_8 = new JTextField();
		textField_8.setColumns(10);
		textField_8.setBounds(180, 264, 344, 28);
		centerpanel.add(textField_8);

		textField_9 = new JTextField();
		textField_9.setColumns(10);
		textField_9.setBounds(180, 294, 344, 28);
		centerpanel.add(textField_9);

		JLabel lblVorname = new JLabel("Vorname");
		lblVorname.setBounds(309, 30, 61, 16);
		centerpanel.add(lblVorname);

		textField_10 = new JTextField();
		textField_10.setBounds(382, 24, 142, 28);
		centerpanel.add(textField_10);
		textField_10.setColumns(10);

		dlm = new DefaultListModel();
		books = new CheckBoxList();
		books.setModel(dlm);
		// ////////////////////////////////////////////////////////////////////////
		// /////////////////////////////////////////////////////////////////////////////
		// /////////////////////////////////////////////////////////////////////////////

		try {
			Class.forName("com.mysql.jdbc.Driver");
			connection = DriverManager
					.getConnection("jdbc:mysql://win9142.informatik.uni-wuerzburg.de:3306?user=awesomefireballs&password=jesus");
		} catch (ClassNotFoundException e) {

			e.printStackTrace();
		} catch (SQLException e) {

			e.printStackTrace();

		}
		try {
			stat = connection.createStatement();
			stat.executeQuery("use `sopra-ws12-awesome_fireballs`;");

			ResultSet idsBooks = stat
					.executeQuery("SELECT idBooks, name, idCreator FROM Books WHERE idUser = "
							+ Test.iduser + ";");

			while (idsBooks.next()) {

				CheckboxBook temp = new CheckboxBook(
						idsBooks.getInt("idBooks"), idsBooks.getString("name"),
						idsBooks.getInt("idCreator"));

				// Fuegt alle Personen interner Liste zu um spaeter wieder auf
				// id
				// zurueckgreifen zu koennen.
				llbooks.add(temp);

				JCheckBoxWithObject check = new JCheckBoxWithObject(temp);

				dlm.addElement(check);

			}

		} catch (SQLException e1) {
			e1.printStackTrace();
		}

		JScrollPane bookscroller = new JScrollPane(books);
		bookscroller.setBounds(180, 324, 344, 28 * 3);
		// bookscroller.setPreferredSize(new Dimension(280, 570));
		centerpanel.add(bookscroller);

		JButton btnKontaktHinzufgen = new JButton("Kontakt Hinzufügen");
		btnKontaktHinzufgen.setBounds(347, 331, 177, 29);
		centerpanel.add(btnKontaktHinzufgen);

		// ActionListener f�r Kontakt hinzuf�gen

		ActionListener bu = new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {

				@SuppressWarnings("rawtypes")
				SwingWorker worker = new SwingWorker() {
					@SuppressWarnings("unchecked")
					@Override
					public Object doInBackground() {
						try {
							Class.forName("com.mysql.jdbc.Driver");
							connection = DriverManager
									.getConnection("jdbc:mysql://win9142.informatik.uni-wuerzburg.de:3306?user=awesomefireballs&password=jesus");

						} catch (ClassNotFoundException e) {
							e.printStackTrace();
						} catch (SQLException e) {
							e.printStackTrace();
							return false;
						}

						Statement stat = null;

						// //////// Date auslesen //////////

						int aY = 0;
						int aM = 0;
						int aD = 0;

						if (jahr.getSelectedIndex() != 0
								&& monat.getSelectedIndex() != 0
								&& tag.getSelectedIndex() != 0) {

							aY = Integer.parseInt((String) jahr
									.getSelectedItem());

							aM = monat.getSelectedIndex();
							aD = tag.getSelectedIndex();

						}

						// Prüft ob der Monat so viele Tage hat.

						if (aD > monthLength(new Date(aY - 1900, aM - 1, 1))) {

							new NotifyFrame(
									"Dieser Monat besitzt diesen Tag nicht.")
									.setVisible(true);
						}

						else {

							Date setDate = null;
							if (aY != 0 && aM != 0 && aD != 0) {
								setDate = makeDate(aY, aM, aD);
							}

							try {
								stat = connection.createStatement();

								String fname = textField.getText();
								String lname = textField_10.getText();
								String street = textField_1.getText();
								String zip = textField_2.getText();
								String town = textField_3.getText();
								String email = textField_4.getText();
								// String bday = textField_5.getText();
								String telehome = textField_6.getText();
								String telework = textField_7.getText();
								String fax = textField_8.getText();
								String cell = textField_9.getText();

								// Formt das Date in einen korrekten String.
								SimpleDateFormat sdf = new SimpleDateFormat(
										"yyyy-MM-dd");

								String bday = "";

								if (setDate != null) {
									StringBuilder sB = new StringBuilder(
											sdf.format(setDate));
									bday = sB.toString();
								}

								System.out.println(bday);

								stat.executeQuery("use `sopra-ws12-awesome_fireballs`;");
								int idAdress = 0;
								ResultSet rs = stat
										.executeQuery("SELECT idAdress FROM `sopra-ws12-awesome_fireballs`.`Adress`ORDER BY idAdress DESC LIMIT 1;");
								while (rs.next()) {
									idAdress = rs.getInt(1) + 1;
								}

								// ResultSet party = stat
								// .executeQuery("SELECT COUNT(idAdress) FROM `sopra-ws12-awesome_fireballs`.Adress;");
								//
								// while (party.next()) {
								// idAdress = party.getInt(1) + 1;
								// }
								connection.setAutoCommit(false);
								PreparedStatement pstmt = connection
										.prepareStatement("INSERT INTO Adress VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
								pstmt.setInt(1, idAdress);
								pstmt.setString(2, fname);
								pstmt.setString(3, lname);
								pstmt.setString(4, street);
								pstmt.setString(5, zip);
								pstmt.setString(6, town);
								pstmt.setString(7, email);
								pstmt.setString(8, bday);
								pstmt.setString(9, telehome);
								pstmt.setString(10, telework);
								pstmt.setString(11, fax);
								pstmt.setString(12, cell);
								pstmt.addBatch();

								PreparedStatement psentrys = connection
										.prepareStatement("INSERT INTO Entrys VALUES( ?, ?, ?)");

								int idEntrys = 0;
								ResultSet entrys = stat
										.executeQuery("SELECT idEntrys FROM `sopra-ws12-awesome_fireballs`.`Entrys`ORDER BY idEntrys DESC LIMIT 1;");
								while (entrys.next()) {
									idEntrys = entrys.getInt(1) + 1;
								}

								// ///neuer Teil für Adressbücher//////
								LinkedList idadd = new LinkedList<Integer>();

								for (int i = 0; i < dlm.size(); i++) {
									JCheckBoxWithObject temp = (JCheckBoxWithObject) dlm
											.get(i);
									if (temp.isSelected() == true) {
										CheckboxBook temp2 = (CheckboxBook) temp
												.getObject();
										idadd.add(temp2.getIdBooks());
									}

								}

								pstmt.executeBatch();

								for (int i = 0; i < idadd.size(); i++) {
									psentrys.setInt(1, idEntrys + i);
									psentrys.setInt(2, idAdress);
									psentrys.setInt(3, (Integer) idadd.get(i));
									psentrys.addBatch();
									System.out.println(psentrys.toString());
								}

								psentrys.executeBatch();
								connection.commit();
								connection.setAutoCommit(true);
							} catch (SQLException e) {
								e.printStackTrace();
							}
							return stat;

						}
						return null;
					}

					@Override
					public void done() {
						dispose();

					}
				};
				worker.execute();

			}

		};

		btnKontaktHinzufgen.addActionListener(bu);

	}

	/*
	 * Macht aus int vars ein Date.
	 */
	@SuppressWarnings("deprecation")
	public static Date makeDate(int year, int month, int day) {

		return new Date(year - 1900, month - 1, day);

	}

	// Ermittelt Laenge des Monats.

	@SuppressWarnings("deprecation")
	public static int monthLength(Date d) {

		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.YEAR, d.getYear());
		cal.set(Calendar.MONTH, d.getMonth());
		cal.set(Calendar.DATE, d.getDate());

		return cal.getActualMaximum(Calendar.DAY_OF_MONTH);
	}
}
